<template>
    <div class="app-container">
        <base-info :opmode="mode" ref="baseInfoForm" />

        <financial-info :opmode="mode" ref="financialForm" />

        <qualification-info :opmode="mode" ref="qualificationInfoForm" />

        <el-row type="flex" justify="end">
            <el-button type="primary" @click="saveData">{{
                this.mode ? '修改' : '保 存'
            }}</el-button>
            <el-button @click="cancelData">取 消</el-button>
        </el-row>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import baseInfo from './components/baseInfo';
import financialInfo from './components/financialInfo';
import qualificationInfo from './components/qualificationInfo';
import { createSupplier, getSupplierDetail, updateSupplier } from '@/api/supplier';

export default {
    name: 'addSupplierInfo',
    computed: {
        ...mapGetters(['supplierDetailInfo'])
    },
    components: { baseInfo, qualificationInfo, financialInfo },
    created() {
        let pathStr = this.$route.path;
        // console.log('pathStr', pathStr);
        if (pathStr.indexOf('update') > -1) {
            this.mode = 1; // 改为修改模式
            this.modSupplierId = this.$route.params.id;
            // console.log('params goodid', this.modSupplierId);
            if (this.modSupplierId == null || this.modSupplierId == undefined) {
                this.$router.go('/404');
            }
            this.supplierDetail(this.modSupplierId); // 发布数据
        } else if (pathStr.indexOf('addProduct') > -1) {
            this.mode = 0; // 改为添加模式
        }
    },

    data() {
        return {
            requestData: '',
            mode: 0, // mode 为0 为添加状态， mode 为1 为修改状态
            initialData: {}
        };
    },
    methods: {
        saveData() {
            let baseInfoForm = this.$refs['baseInfoForm'].validateForm();
            let financialForm = this.$refs['financialForm'].validateForm();
            let qualificationInfoForm = this.$refs['qualificationInfoForm'].validateForm();
            Promise.all([baseInfoForm, financialForm, qualificationInfoForm]).then(
                res => {
                    //  // console.log(this.$refs["baseInfoForm"]);
                    if (res) {
                        if (this.mode === 0) {
                            this.createSupplier();
                        } else {
                            this.updateSupplier();
                        }
                    }
                },
                err => {
                    this.$message.error('请按要求填写表单');
                }
            );
        },

        createSupplier() {
            let reqData = this.getFormData(); // 目前的数据
            // console.log('resData', reqData);
            createSupplier(reqData).then(res => {
                if (res.data && res.data.success) {
                    this.$message.success('新增商品成功');
                    this.$router.back(-1); // 回到原来的路由
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        updateSupplier() {
            let reqData = this.getUpdateRequestData();
            updateSupplier(reqData).then(res => {
                if (res.data.success == true) {
                    this.$message.success('修改成功');
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        supplierDetail(id) {
            id = id ? id : this.$route.path;
            getSupplierDetail(id).then(res => {
                if (res.data.success == true) {
                    // 获取成功
                    this.modGoodDetailInfo = res.data.data;
                    return this.$store.dispatch('SetSupplierDetail', {id,...res.data.data}).then(() => {
                        this.initialData = this.getFormData();
                        // console.log('initialData', this.initialData);
                    }); //发布数据
                    // // console.log(this.supplierDetailInfo)
                } else {
                    this.$message.error(res.data.msg);
                    this.$router.back(-1);
                }
            });
        },
        cloneDeep(obj) {
            return JSON.parse(JSON.stringify(obj));
        },
        getFormData() {
            // 深拷贝， 改变格式不影响原先值
            let baseformData = this.$refs['baseInfoForm'].baseInfoForm;
            let financial = this.$refs['financialForm'].baseInfoForm;
            let qualificationInfo = this.$refs['qualificationInfoForm'].baseInfoForm
      
            this.requestData = {
                ...baseformData,
                ...financial,
                ...qualificationInfo
            };

            return this.requestData;
        },
        getUpdateRequestData() {
            let beforeObj = this.initialData;
            let afterObj = this.getFormData();
            let remainPictureURL = [];
            const dic = ['protocals', 'licenses', 'others'];
           
            dic.forEach(key=>{
                let fileArr =[];
                afterObj[key].forEach(el=>{
                    if (el instanceof File) {
                        fileArr.push(el)
                    }else {
                        remainPictureURL.push(el)
                    }
                })
                afterObj[key] = fileArr;
            })
            afterObj.delAttachmentIds = this.compareAndGetImgDel(remainPictureURL)
            return afterObj;
        },
        compareAndGetAdd(beforeArr, afterArr) {
            return afterArr.filter(el => !beforeArr.includes(el));
        },
        compareAndGetDel(beforeArr, afterArr) {
            return beforeArr.filter(el => !afterArr.includes(el));
        },
        compareAndGetImgDel(afterUrls) {
             const dic = ['protocals', 'licenses', 'others'];
            let imgInfoArr = [];
            dic.forEach(key=>{
                if (this.supplierDetailInfo[key]) {
                    imgInfoArr.push(...this.supplierDetailInfo[key])
                }
            })
            let deleteArr = imgInfoArr.filter(el => !afterUrls.includes(el.resourceUrl));
            return deleteArr.map(el => el.id);
        },
        cancelData() {
            this.$router.back(-1); // 回到原来的路由
        }
    }
};
</script>

<style scoped>
.operate-button {
    width: 900px;
    margin: 15px;
}
</style>
